package com.yqya.sorting.basic.selection.algo;

/**
 * 选择排序
 *
 * @author Kevin
 * @date 2018-06-19
 */
public class SelectionSort {

    private SelectionSort() {

    }

    public static void sort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            // 寻找[i, n)区间里的最小值的索引
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[i]) {
                    minIndex = j;
                }
            }

            swap(arr, i, minIndex);
        }
    }


    private static void swap(int[] arr, int i, int j) {
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {
        int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
        SelectionSort.sort(arr);

        StringBuilder res = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            res.append(arr[i] + ", ");
        }
        System.out.println(res.toString());
        // 输出结果：
        // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    }

}
